//
//  HCConsoleLogger.m
//  HCLog
//
//  Created by 韩昌 on 2017/7/11.
//  Copyright © 2017年 Han Chang. All rights reserved.
//

#import "HCConsoleLogger.h"
#import "HCConsoleLogFormatter.h"
#import <unistd.h>
#import <sys/uio.h>

@implementation HCConsoleLogger

@synthesize logFormatter = _logFormatter;

+ (instancetype)sharedInstance
{
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    
    return sharedInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _logFormatter = [[HCConsoleLogFormatter alloc] init];
    }
    return self;
}

- (NSString *)loggerName
{
    return @"org.hanchang.log.consoleLogger";
}

- (void)logMessage:(HCLogMessage *)logMessage
{
    NSString *message = [_logFormatter formatLogMessage:logMessage];
    
    if (message) {
        NSUInteger msgLen = [message lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
        const char *msg = [message UTF8String];
        
        struct iovec v[2];

        v[0].iov_base = (void *)msg;
        v[0].iov_len = msgLen;

        v[1].iov_base = "\n";
        v[1].iov_len = 1;
        
        writev(STDERR_FILENO, v, 2);
    }
}

@end
